package cn.com.dashihui.pay.ZY;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.rsa.sdk.utils.Base64;
import cn.com.dashihui.api.common.PayCode;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.pay.SQ.Kit.ParamUtils;
import net.sf.json.JSONObject;


//查询签约
public class ZYPay {


	
	//MT1305出入金查询    返回userid交互id
	public static JSONObject queryMoneyOrder(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("BEGIN_DATA", "");
		map.put("END_DATA", "");
		map.put("SYSID", "");
		map.put("COMPANY_ID", "");
		map.put("PAGE", "");
		map.put("SIZE", "");
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.QUERYMONEY_ORDER);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost2(json,httppost);
	}
	//MT1305开户    返回userid交互id
	public static JSONObject regist(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("phoneNumber", ParamUtils.toString(dataMap.get("phoneNumber")));
		map.put("password", ParamUtils.toString(dataMap.get("password")));
		map.put("TJFIRMID", PayCode.Parameter.TJFIRMID);
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.REGIST);
		reqMap.put("params", map);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
		 
	}
	//MA1000修改密码
	public static JSONObject changePwd(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("phoneNumber", ParamUtils.toString(dataMap.get("phoneNumber")));
		map.put("pwd", ParamUtils.toString(dataMap.get("pwd")));
		map.put("VERIFYCODE", ParamUtils.toString(dataMap.get("VERIFYCODE")));
		map.put("operType", ParamUtils.toString(dataMap.get("operType")));
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.CHANGEPWD);
		reqMap.put("params", map);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
		 
	}
	//MT1310获取验证码    返回userid交互id
	public static JSONObject getCode(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("phoneNumber", ParamUtils.toString(dataMap.get("phoneNumber")));
		map.put("CAPTCHA", ParamUtils.toString(dataMap.get("CAPTCHA")));
		map.put("CAPTCHA_TOKEN", ParamUtils.toString(dataMap.get("CAPTCHA_TOKEN")));
		map.put("CAPTCHA_ACTION","");
		map.put("TPLID", PayCode.Parameter.TPLID);
		map.put("CLANGUAGE", "");
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.GETCODE);
		reqMap.put("params", map);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
		 
	}
	//MT1002获取图形验证码    返回userid交互id   
	public static JSONObject findImage() {
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.FINDIMAGE);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
		
	}
   	
	//MT1100登录  返回token登录凭证 
	public static JSONObject login(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("account", ParamUtils.toString(dataMap.get("account")));
		map.put("pwd", ParamUtils.toString(dataMap.get("pwd")));
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api",  PayCode.API.LOGIN);
		reqMap.put("params", map);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
		 
	}
	//MT1103修改支付密码
	public static JSONObject updatePWD(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("pwd", ParamUtils.toString(dataMap.get("pwd")));
		map.put("newPwd", ParamUtils.toString(dataMap.get("newPwd")));
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api",  PayCode.API.UPDATEPWD);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
        return sendPost2(json,httppost);
	}
	
	
	//ST030003下单状态  
	public static JSONObject orderstate(Map<String,String> dataMap) {
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("sys_code", PayCode.Parameter.SYS_CODE);
//		map.put("source_type", PayCode.Parameter.SOURCE_TYPE);//订单类型
//		map.put("source_id", PayCode.Parameter.SOURCE_ID);//来源id
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));//下单标号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.ORDERSTATE);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost2(json,httppost);
	}
	//ST030004下单详情
	public static void orderDetail(Map<String,String> dataMap) throws Exception{
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("sys_code", PayCode.Parameter.SYS_CODE);
		map.put("source_type", PayCode.Parameter.SOURCE_TYPE);//订单类型
		map.put("source_id", ParamUtils.toString(dataMap.get("order_id")));//来源id
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));//下单标号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.ORDERDETAIL);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
         sendPost2(json,httppost);
	}
	//ZB0102余额查询
	public static JSONObject find(Map<String,String> dataMap) {
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("COMPANY_ID", PayCode.Parameter.COMPANY_ID);//子账号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.FINDMONRY);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
        return  sendPost2(json,httppost);
	}
	//ST030047下单 
	public static JSONObject createOrder(Map<String,String> dataMap) throws Exception {
		//请求参数 
		Map<String,String> map = new HashMap<String,String>();
		map.put("downmer_code", PayCode.Parameter.TJFIRMID);
		map.put("version", PayCode.Parameter.VERSION);
		map.put("terminal_type", ParamUtils.toString(dataMap.get("terminal_type")));
		map.put("terminal_num",ParamUtils.toString(dataMap.get("terminal_num")));
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));
		map.put("order_detail", "");
		map.put("order_money", ParamUtils.toString(dataMap.get("order_money")));
		map.put("order_time", DatetimeKit.getFormatDate(new Date(),null));
		map.put("order_ip", ParamUtils.toString(dataMap.get("order_ip")));
		map.put("notify_url", PayCode.Parameter.NOTIFYURL);
		map.put("pay_firmid", ParamUtils.toString(dataMap.get("pay_firmid")));
		map.put("payee_firmid",PayCode.Parameter.TJFIRMID);
		map.put("is_points","");
		map.put("callback_url", PayCode.Parameter.CALLBACKURL);
		System.out.println("-----------签名原文"+EncryUtils.createLinkString(map).toString());
		String sign = EncryUtils.sign(map, PayCode.Key.PRIVATEKEY);
		System.out.println("-----------签名："+sign);
		map.put("sign_str",sign);
		map.put("sys_code", PayCode.Parameter.SYS_CODE);
		map.put("model_type", PayCode.Parameter.MODELTYPE);
		map.put("trans_scene", PayCode.Parameter.TRANSSCENE);
		map.put("source_type", PayCode.Parameter.SOURCE_TYPE);
		map.put("source_id",  ParamUtils.toString(dataMap.get("order_id")));
		map.put("order_type", ParamUtils.toString(dataMap.get("order_type")));
		map.put("pay_firmname", ParamUtils.toString(dataMap.get("pay_firmname")));
		map.put("pay_phone", ParamUtils.toString(dataMap.get("pay_phone")));
		map.put("payee_firmname", PayCode.Parameter.FIRMNAME);
//		map.put("goods_detail", ParamUtils.toString(dataMap.get("goods_detail")));
		map.put("order_fee", ParamUtils.toString(dataMap.get("order_fee")));
//		map.put("order_detail", ParamUtils.toString(dataMap.get("order_detail")));
//		map.put("order_timeout", ParamUtils.toString(dataMap.get("order_timeout")));
//		map.put("subord_detail", ParamUtils.toString(dataMap.get("subord_detail")));
		Map<String,String> map2 = new HashMap<String,String>();
		map2.put("ACCT_TYPE", PayCode.Parameter.ACCTTYPE);
		String json2 = JSONObject.fromObject(map2).toString();
		json2 = new String(Base64.encodeBase64(json2.getBytes()), PayCode.Parameter.ENCODE);
		json2 = json2.replaceAll("\r", "").replaceAll("\n", "").replace("+", "%2B").replace("=", "%3D");
		map.put("extend", json2);
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.CREATEORDER);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
		// 创建参数队列    
        return sendPost2(json,httppost);		
	}
	//ST030047提现
	public static JSONObject createOrderE(Map<String,String> dataMap) throws Exception {
		//请求参数 
		Map<String,String> map = new HashMap<String,String>();
		map.put("downmer_code", PayCode.Parameter.TJFIRMID);
		map.put("version", PayCode.Parameter.VERSION);
		map.put("terminal_type", ParamUtils.toString(dataMap.get("terminal_type")));
		map.put("terminal_num",ParamUtils.toString(dataMap.get("terminal_num")));
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));
		map.put("order_detail", "");
		map.put("order_money", ParamUtils.toString(dataMap.get("order_money")));
		map.put("order_time", DatetimeKit.getFormatDate(new Date(),null));
		map.put("order_ip", ParamUtils.toString(dataMap.get("order_ip")));
		map.put("notify_url", PayCode.Parameter.NOTIFYURL);
		map.put("pay_firmid", ParamUtils.toString(dataMap.get("pay_firmid")));
		map.put("payee_firmid",ParamUtils.toString(dataMap.get("pay_firmid")));
		map.put("is_points","");
		map.put("callback_url", PayCode.Parameter.CALLBACKURL);
		System.out.println("-----------签名原文"+EncryUtils.createLinkString(map).toString());
		String sign = EncryUtils.sign(map, PayCode.Key.PRIVATEKEY);
		System.out.println("-----------签名："+sign);
		map.put("sign_str",sign);
		map.put("sys_code", PayCode.Parameter.SYS_CODE);
		map.put("model_type", PayCode.Parameter.MODELTYPE);
		map.put("trans_scene", PayCode.Parameter.TRANSSCENE);
		map.put("source_type", PayCode.Parameter.SOURCE_TYPE);
		map.put("source_id",  ParamUtils.toString(dataMap.get("order_id")));
		map.put("order_type", ParamUtils.toString(dataMap.get("order_type")));
		map.put("pay_firmname", ParamUtils.toString(dataMap.get("pay_firmname")));
		map.put("pay_phone", ParamUtils.toString(dataMap.get("pay_phone")));
		map.put("payee_firmname", PayCode.Parameter.FIRMNAME);
//			map.put("goods_detail", ParamUtils.toString(dataMap.get("goods_detail")));
		map.put("order_fee", ParamUtils.toString(dataMap.get("order_fee")));
//			map.put("order_detail", ParamUtils.toString(dataMap.get("order_detail")));
//			map.put("order_timeout", ParamUtils.toString(dataMap.get("order_timeout")));
//			map.put("subord_detail", ParamUtils.toString(dataMap.get("subord_detail")));
		Map<String,String> map2 = new HashMap<String,String>();
		map2.put("ACCT_TYPE", PayCode.Parameter.ACCTTYPE);
		String json2 = JSONObject.fromObject(map2).toString();
		json2 = new String(Base64.encodeBase64(json2.getBytes()), PayCode.Parameter.ENCODE);
		json2 = json2.replaceAll("\r", "").replaceAll("\n", "").replace("+", "%2B").replace("=", "%3D");
		map.put("extend", json2);
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.CREATEORDER);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost(PayCode.Parameter.URL+"?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
		// 创建参数队列    
        return sendPost2(json,httppost);		
	}
	public static  JSONObject  sendPost( String json) {
		CloseableHttpClient httpclient = null ;
		JSONObject s = null;
        try {  
        	//使用默认配制创建httpclient实例
//            CloseableHttpClient httpclient= HttpClients.createDefault();
        	/** 创建httpclient实例，自行设置
        	 * connectionRequestTimeout  从连接处获取数据的超时时间
        	 * setConnectTimeout		  连接上服务器的时间
        	 * socketTimeout			 服务器返回数据的时间
        	 */
            httpclient =HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
        			.setConnectionRequestTimeout(2000).setConnectTimeout(2000)
        			.setSocketTimeout(2000).build()).build();
        	// 创建httppost
            HttpPost httppost= new HttpPost(PayCode.Parameter.URL);
           
        	System.out.println("请求:    "+json);
        	 System.out.println("executing request " + httppost.getURI());  
        	 
        	StringEntity stringEntity = new StringEntity(json, ContentType.create(PayCode.Parameter.HEADER, PayCode.Parameter.ENCODE));  
        	httppost.setEntity(stringEntity);  
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try {
//            	JSONObject js = null;
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	  String str = EntityUtils.toString(entity, PayCode.Parameter.ENCODE);
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str);
//                      System.out.println("Response content: " + JSONObject.fromObject(str.substring(1, str.length()-1)));
                      System.out.println("--------------------------------------");
                      s =  JSONObject.fromObject(str.substring(1, str.length()-1));
                  }
                  return s;
            } finally {
                response.close();
               
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	 // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return s;
        
	}
	
	public static  JSONObject  sendPost2( String json, HttpPost httppost) {
		CloseableHttpClient httpclient = null ;
		JSONObject s = null;
        try {  
        	//使用默认配制创建httpclient实例
//            CloseableHttpClient httpclient= HttpClients.createDefault();
        	/** 创建httpclient实例，自行设置
        	 * connectionRequestTimeout  从连接处获取数据的超时时间
        	 * setConnectTimeout		  连接上服务器的时间
        	 * socketTimeout			 服务器返回数据的时间
        	 */
            httpclient =HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
        			.setConnectionRequestTimeout(2000).setConnectTimeout(2000)
        			.setSocketTimeout(2000).build()).build();
        	// 创建httppost
        	System.out.println("请求:    "+json);
        	System.out.println("请求网址 " + httppost.getURI());  
        	StringEntity stringEntity = new StringEntity(json, ContentType.create(PayCode.Parameter.HEADER, PayCode.Parameter.ENCODE));  
            httppost.setEntity(stringEntity);  
            Scanner scanner = new Scanner(stringEntity.getContent());
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try {
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	  String str = EntityUtils.toString(entity, PayCode.Parameter.ENCODE);
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str);
//                      System.out.println("Response content: " + JSONObject.fromObject(str.substring(1, str.length()-1)));
                      System.out.println("--------------------------------------");
                      s =  JSONObject.fromObject(str.substring(1, str.length()-1));
                  }
                  return s;
            } finally {
                response.close();
               
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	 // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
        
	}
	
	
	
}
